// #region    导入模块
const gulp = require("gulp");
const less = require("gulp-less");
const concat = require("gulp-concat");
const uglify = require("gulp-uglify");
const rename = require("gulp-rename");
const cleanCSS = require("gulp-clean-css");
const htmlMin = require("gulp-htmlmin");
const browserSync = require("browser-sync").create();
const del = require("del");
// #endregion 导入模块

// #region    配置源文件和目标文件路径
const paths = {
  watch: {
    dest: "./assets/",
  },
  less: {
    src: "./src/styles/less/*.less",
    dest: "./src/styles/css/",
  },
  styles: {
    src: "./src/styles/css/*.css",
    dest: "./assets/styles/",
  },
  scripts: {
    src: "./src/scripts/*.js",
    dest: "./assets/scripts/",
  },
  html: {
    src: "./src/index.html",
    dest: "./assets/",
  },
};
// #endregion 配置源文件和目标文件路径

// #region    清理目标文件夹
function clean() {
  return del([
    `${paths.less.dest}/*`,
    `${paths.styles.dest}/*`,
    `${paths.scripts.dest}/*`,
    `${paths.html.dest}/*.html`,
  ]);
}
// #endregion 清理目标文件夹

// #region    定义任务
function less_to_css() {
  return gulp.src(paths.less.src).pipe(less()).pipe(gulp.dest(paths.less.dest));
}
function styles() {
  return gulp
    .src(paths.styles.src)
    .pipe(concat("concat.css"))
    .pipe(cleanCSS())
    .pipe(
      rename({
        basename: "main",
        suffix: ".min",
      }),
    )
    .pipe(gulp.dest(paths.styles.dest));
}

function scripts() {
  return gulp
    .src(paths.scripts.src)
    .pipe(concat("main.min.js"))
    .pipe(uglify().pipe(gulp.dest(paths.scripts.dest)));
}

function min_html() {
  return gulp
    .src(paths.html.src)
    .pipe(htmlMin({ collapseWhitespace: true }))
    .pipe(gulp.dest(paths.html.dest));
}

function start() {
  browserSync.init({
    server: {
      baseDir: paths.watch.dest,
    },
  });
}

function watch() {
  start();
  gulp.watch(paths.less.src, less_to_css).on("change", browserSync.reload);
  gulp.watch(paths.styles.src, styles).on("change", () => {
    console.log("css文件发生了变化");
    browserSync.reload();
  });
  gulp.watch(paths.scripts.src, scripts).on("change", browserSync.reload);
  gulp.watch(paths.html.src, min_html).on("change", browserSync.reload);
}

// #endregion 定义任务

// #region    指定任务运行的模式
// const bulid = gulp.series(clean, gulp.parallel(styles, scripts));
const build = gulp.series(
  clean,
  less_to_css,
  gulp.parallel(styles, scripts, min_html),
);
// #endregion 指定任务运行的模式

// #region    导出
exports.clean = clean;
exports.less = less_to_css;
exports.styles = styles;
exports.scripts = scripts;
exports.html = min_html;
exports.watch = watch;
exports.build = build;
exports.default = watch;
// #endregion 导出
